<script setup>
import { onMounted, ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { getCourse, updateCourse, dropCourse, insertCourse } from "@/apis/manger";

const allCourses = ref([]); // 用于存储所有课程
const courses = ref([]); // 用于当前页显示的课程
let queryName = ref(null);
let queryCredits = ref(null);
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页条数
const totalCourses = computed(() => allCourses.value.length); // 课程总数

// 控制对话框的显示
const isEditDialogVisible = ref(false);
const isAddDialogVisible = ref(false);

// 编辑或新增课程的临时对象
const currentCourse = ref({
  id: null,
  name: "",
  description: "",
  credits: 0,
});

onMounted(() => {
  fetchCourses();
});

// 从后端获取课程列表的函数
async function fetchCourses() {
  try {
    let result = await getCourse(queryName.value || null, queryCredits.value);
    console.log(result);
    allCourses.value = result.result;
    updateCourses();
  } catch (error) {
    ElMessage.error("获取课程列表失败");
    console.error("Error fetching courses:", error);
  }
}

// 更新当前页的课程列表
function updateCourses() {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  courses.value = allCourses.value.slice(start, end);
}

// 在查询条件改变时调用 fetchCourses
const onQueryChange = () => {
  currentPage.value = 1; // 重置页码为第一页
  fetchCourses();
};

// 分页变化时调用
const onPageChange = (page) => {
  currentPage.value = page;
  updateCourses();
};

const onPageSizeChange = (size) => {
  pageSize.value = size;
  updateCourses();
};

// 编辑课程
const editCourse = (course) => {
  currentCourse.value = { ...course };
  isEditDialogVisible.value = true; // 显示编辑对话框
};

// 保存课程编辑
const saveCourseEdit = async () => {
  try {
    let result = await updateCourse(currentCourse.value);
    if (result.message === "200") {
      allCourses.value = allCourses.value.map((c) =>
          c.id === currentCourse.value.id ? currentCourse.value : c
      );
      updateCourses();
      ElMessage.success("编辑成功");
      isEditDialogVisible.value = false;
    } else {
      ElMessage.error("编辑失败");
    }
  } catch (error) {
    ElMessage.error("编辑失败");
    console.error("Error editing course:", error);
  }
};

// 删除课程
const deleteCourse = async (course) => {
  try {
    let result = await dropCourse(course);
    if (result.message === "200") {
      allCourses.value = allCourses.value.filter((c) => c.id !== course.id);
      updateCourses();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error( "该课程已经被选，不能删除");
    }
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("Error deleting course:", error);
  }
};

// 新增课程
const addCourse = () => {
  currentCourse.value = { id: null, name: "", description: "", credits: 0 }; // 清空临时对象
  isAddDialogVisible.value = true; // 显示新增对话框
};

// 保存新增的课程
const saveNewCourse = async () => {
  try {
    let result = await insertCourse(currentCourse.value);
    if (result.message === "200") {
      allCourses.value.push(result.result);
      updateCourses();
      ElMessage.success("新增成功");
      isAddDialogVisible.value = false;
    } else {
      ElMessage.error("新增失败");
    }
  } catch (error) {
    ElMessage.error("新增失败");
    console.error("Error adding course:", error);
  }
};
</script>

<template>
  <el-card>
    <div style="margin-bottom: 16px;">
      <el-input
          v-model="queryName"
          placeholder="查询课程名称"
          style="width: 200px; margin-right: 16px;"
      ></el-input>
      <el-input-number
          v-model="queryCredits"
          placeholder="查询学分"
          style="width: 120px;"
      ></el-input-number>
      <el-button type="primary" @click="onQueryChange">查询</el-button>
    </div>
    <el-button type="primary" @click="addCourse">新增课程</el-button>
    <el-table :data="courses" style="width: 100%">
      <el-table-column label="课程名称" prop="name"></el-table-column>
      <el-table-column label="课程编号" prop="id"></el-table-column>
      <el-table-column label="课程简介" prop="description"></el-table-column>
      <el-table-column label="学分" prop="credits"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editCourse(scope.row)" size="small">编辑</el-button>
          <el-button @click="deleteCourse(scope.row)" size="small" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalCourses"
        @current-change="onPageChange"
        @size-change="onPageSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px;"
    ></el-pagination>

    <!-- 编辑课程对话框 -->
    <el-dialog v-model="isEditDialogVisible" title="编辑课程">
      <el-form :model="currentCourse">
        <el-form-item label="课程名称">
          <el-input v-model="currentCourse.name"></el-input>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input v-model="currentCourse.description"></el-input>
        </el-form-item>
        <el-form-item label="学分">
          <el-input-number v-model="currentCourse.credits"></el-input-number>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCourseEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增课程对话框 -->
    <el-dialog v-model="isAddDialogVisible" title="新增课程">
      <el-form :model="currentCourse">
        <el-form-item label="课程名称">
          <el-input v-model="currentCourse.name"></el-input>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input v-model="currentCourse.description"></el-input>
        </el-form-item>
        <el-form-item label="学分">
          <el-input-number v-model="currentCourse.credits"></el-input-number>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="isAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNewCourse">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
</style>
